package com.stylefeng.guns.modular.system.task;

import java.net.URL;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.stylefeng.guns.modular.system.dao.*;
import com.stylefeng.guns.modular.system.model.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.common.constant.state.KpMethod;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.core.util.HttpClientUtil;
import com.stylefeng.guns.core.util.HttpsClient;
import com.stylefeng.guns.core.util.RestUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;
import com.stylefeng.guns.modular.system.service.IGdhsService;
import com.stylefeng.guns.modular.system.service.IGpcService;
import com.stylefeng.guns.modular.system.service.IGpdataService;
import com.stylefeng.guns.modular.system.service.IHybrankDetailService;

@Service
public class GpcImportTask{

	private Logger log = LoggerFactory.getLogger(GpcImportTask.class);
	
	@Autowired
	private GpcMapper gpcMapper;
	
	@Autowired
	private GdpriceMapper gdpriceMapper;

	@Autowired
	private JjGpcMapper jjGpcMapper;
	
	@Autowired
	private HsgtMapper hsgtMapper;
	
	@Autowired
	private IGdhsService iGdhsService;
	
	@Autowired
    private IGpdataService gpdataService;
	
	@Autowired
    private IGpcService gpcService;

	@Autowired
	private NbGpcWtMapper gpcWtMapper;

	@Autowired
	private IHybrankDetailService hybrankDetailService;
	
	@Autowired
	private ParamsMapper paramsMapper;
	
	private static final HttpClientUtil clientUtil = new HttpClientUtil();


	public void execute(boolean isHoliday) {
		if(isHoliday){
			String date = DateUtil.format(new Date(), "yyyy-MM-dd");
			List<Map<String, Object>> lists = hybrankDetailService.selectNgByDate(date);
			for(Map<String, Object> vMaps : lists){
				String gScode = (String)vMaps.get("gScode");
				String gSalesCode = (String)vMaps.get("gSalesCode");
				String gSalesDetail = (String)vMaps.get("gSalesDetail");
				Date gTdate = (Date)vMaps.get("gTdate");

				String[] gSalesCodes = StringUtils.split(gSalesCode,",");

				Gdhs gdhs = new Gdhs();
				gdhs.setgDm(gScode);
				gdhs = iGdhsService.getGdhsByDate(gdhs);
				if(gdhs == null) continue;

//				double gzsz = Math.abs((gdhs.getgZsz() / 100000000));
//				if(gzsz >130) continue;

				Wrapper<Gpdata> wrapper = new EntityWrapper<Gpdata>();
				wrapper.eq("g_dm", gScode);
				Gpdata gpdata = gpdataService.selectOne(wrapper);
				if(gpdata == null) continue;

//				if(gpdata.getgIsJjNum() > 0) continue;

				if(gpdata.getgJgcydType().equals("不控盘")) continue;

				Gdprice gdprice = new Gdprice();
				gdprice.setgDm(gScode);
				gdprice.setgTime(gTdate);

				if(StringUtils.contains((String)vMaps.get("gSname"), "ST")){
					continue;
				}

				if(StringUtils.contains((String)vMaps.get("gSname"), "退市")){
					continue;
				}

				List<Gdprice> gdprices = gdpriceMapper.getGdpriceByDateLimit(gdprice);
				double zdf = 0;
				double czdf = 0;
				for(Gdprice v : gdprices){
					zdf+=v.getgZdf();
					if(DateUtil.format(v.getgTime(), "yyyy-MM-dd").equals(DateUtil.format(gTdate, "yyyy-MM-dd"))){
						czdf = v.getgZdf();
					}
				}
				if(zdf < -20){
					continue;
				}

				if(czdf < 2){
					continue;
				}

				Gpc gpc = new Gpc();
				gpc.setgScode(gScode);
				gpc.setgTdate(gTdate);



				gpc = gpcMapper.selectByDate(gpc);
				if(gpc == null){
					gpc = new Gpc();
					gpc.setgYzs(gSalesCodes.length);
					gpc.setgScode(gScode);
					gpc.setgTdate(gTdate);
					gpc.setgSalesDetail(gSalesDetail);
					gpcMapper.insert(gpc);
				}
			}

			List<Map<String, Object>> hsgtLists = hsgtMapper.selectNgByDate(date);
			for(Map<String, Object> vMaps : hsgtLists){
				String gScode = (String)vMaps.get("gScode");
				Date gTdate = (Date)vMaps.get("gTdate");
				Long gSalesCode = (Long)vMaps.get("gSalesCode");

				Gdhs gdhs = new Gdhs();
				gdhs.setgDm(gScode);
				gdhs = iGdhsService.getGdhsByDate(gdhs);
				if(gdhs == null) continue;

				Wrapper<Gpdata> wrapper = new EntityWrapper<Gpdata>();
				wrapper.eq("g_dm", gScode);
				Gpdata gpdata = gpdataService.selectOne(wrapper);
				if(gpdata == null) continue;

				//if(gpdata.getgIsJjNum() > 0) continue;

				if(gpdata.getgJgcydType().equals("不控盘")) continue;

				Gdprice gdprice = new Gdprice();
				gdprice.setgDm(gScode);
				gdprice.setgTime(gTdate);

				if(StringUtils.contains((String)vMaps.get("gSname"), "ST")){
					continue;
				}

				if(StringUtils.contains((String)vMaps.get("gSname"), "退市")){
					continue;
				}

				List<Gdprice> gdprices = gdpriceMapper.getGdpriceByDateLimit(gdprice);
				double zdf = 0;
				double czdf = 0;
				for(Gdprice v : gdprices){
					zdf+=v.getgZdf();
					if(DateUtil.format(v.getgTime(), "yyyy-MM-dd").equals(DateUtil.format(gTdate, "yyyy-MM-dd"))){
						czdf = v.getgZdf();
					}
				}
				if(zdf < -19){
					continue;
				}

				if(czdf < 2){
					continue;
				}

				Gpc gpc = new Gpc();
				gpc.setgScode(gScode);
				gpc.setgTdate(gTdate);

				gpc = gpcMapper.selectByDate(gpc);
				if(gpc != null){
					gpc.setgJgs(gpc.getgJgs() + 1);
					gpc.setgScode(gScode);
					gpc.setgTdate(gTdate);
					if(gSalesCode.equals("80601499") || gSalesCode.equals("80403915")){
						gpc.setgSalesDetail(gpc.getgSalesDetail().concat(",海外資金"));
					}else{
						gpc.setgSalesDetail(gpc.getgSalesDetail().concat(",机构专用"));
					}
					gpcMapper.updateById(gpc);
				}else{
					gpc = new Gpc();
					gpc.setgJgs(1);
					gpc.setgScode(gScode);
					gpc.setgTdate(gTdate);
					if(gSalesCode.equals("80601499") || gSalesCode.equals("80403915")){
						gpc.setgSalesDetail("海外資金");
					}else{
						gpc.setgSalesDetail("机构专用");
					}
					gpcMapper.insert(gpc);
				}
			}

			Params params = new Params();
			params.setgUserid("387065");
			params = paramsMapper.selectOne(params);
			if(params != null){
				gpcService.updatefk(DateUtil.getDay(), params.getgToken(), params.getgUserid());
			}


			List<String> gpcs = gpcMapper.selectCodeListByDate(DateUtil.getAfterDayDate(new Date(),"-1"));
			if(CollectionUtils.isEmpty(gpcs)){
				gpcs = gpcMapper.selectCodeListByDate(DateUtil.getAfterDayDate(new Date(),"-3"));
			}
			if(CollectionUtils.isNotEmpty(gpcs)){
				String codes = StringUtils.join(gpcs, ",");
				Hashtable<String, String> paramsMaps = new Hashtable<String, String>();
				paramsMaps.put("a", KpMethod.G.getMethod());
				paramsMaps.put("c", "UserSelectStock");
				paramsMaps.put("StockID", codes);
				paramsMaps.put("CombineID", "0");
				paramsMaps.put("Token", params.getgToken());
				paramsMaps.put("UserID", params.getgUserid());
				String result = HttpsClient.postSSL(ImportContants.getKpDataPathStr(), paramsMaps,false);
				if(StringUtils.isNotEmpty(result)){
					int rcode = JSON.parseObject(result).getInteger("errcode");
					if(rcode == 0){
						gpcs = gpcMapper.selectCodeListByDate(new Date());
						codes = StringUtils.join(gpcs, ",");
						paramsMaps = new Hashtable<String, String>();
						paramsMaps.put("a", KpMethod.H.getMethod());
						paramsMaps.put("c", "UserSelectStock");
						paramsMaps.put("StockIDList", codes);
						paramsMaps.put("CombineID", "0");
						paramsMaps.put("Token", params.getgToken());
						paramsMaps.put("UserID", params.getgUserid());
						result = HttpsClient.postSSL(ImportContants.getKpDataPathStr(), paramsMaps,false);
						if(StringUtils.isNotEmpty(result)){
							rcode = JSON.parseObject(result).getInteger("errcode");
							if(rcode == 0){
								log.info("添加到自选股成功！");
							}
						}
						HttpGet httpGet = HttpClientUtil.getGetRequest();
						try {
							for(int i=0;i<3;i++){
								for(String code : gpcs){
									String day = DateUtils.formatDate(DateUtil.getAfterDayDate(new Date(), "-" + i), "yyyyMMdd");
									if(!RestUtil.isRest(day)){
										continue;
									}
									String url = ImportContants.getJJPathStr(code,day);
										httpGet.setURI(new URL(url).toURI());
										String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
										JSONObject jsonObj = JSON.parseObject(json);
										if (jsonObj.getString("msg").equals("succ")) {
											String desc = jsonObj.getJSONObject("data").getString("desc");
											JSONObject jsonObject = jsonObj.getJSONObject("data").getJSONArray("list").getJSONObject(jsonObj.getJSONObject("data").getJSONArray("list").size()-1);
											double count = jsonObject.getDouble("v2");
											int chl = jsonObject.getIntValue("v1");
											if(chl > 0){
												desc += " 剩余 买 " + chl + " 手";
											}else{
												desc += " 剩余 卖 " + chl + " 手";
											}
											JjGpc jjGpc = new JjGpc();
											jjGpc.setgScode(code);
											jjGpc.setgDate(DateUtil.getAfterDayDate(new Date(), "-" + i));
											jjGpc = jjGpcMapper.selectByDate(jjGpc);
											if(jjGpc == null){
												jjGpc = new JjGpc();
												jjGpc.setgBuy(count);
												jjGpc.setgScode(code);
												jjGpc.setgDate(DateUtil.getAfterDayDate(new Date(), "-" + i));
												jjGpc.setgYdDsc(desc);
												jjGpcMapper.insert(jjGpc);
											}else{
												jjGpc.setgBuy(count);
												jjGpc.setgYdDsc(desc);
												jjGpcMapper.updateById(jjGpc);
											}
										}
								}
							}
							for(String code : gpcs){
								if(code.startsWith("6")){
									continue;
								}
								String resultc = HttpsClient.postSSL(ImportContants.getWtPathStr(code,1), null,true);
								JSONArray jsonArray =  JSON.parseObject(resultc).getJSONArray("List");
								for(int i=0;i<jsonArray.size();i++){
									String v = StringUtils.remove(jsonArray.get(i).toString(), "\"");
									String[] valus = StringUtils.split(StringUtils.substringBetween(v, "[", "]"),",");
									NbGpcWt gpcWt = new NbGpcWt();
									gpcWt.setgScode(code);
									Date nowTime = DateUtil.parseTime(DateUtil.getDay().concat(" ").concat(valus[0]).concat(":00"));
									gpcWt.setgTime(nowTime);
									gpcWt = gpcWtMapper.selectByTime(gpcWt);
									if(gpcWt == null){
										gpcWt = new NbGpcWt();
										gpcWt.setgScode(code);
										gpcWt.setgTime(nowTime);
										gpcWt.setgPrice(Double.valueOf(valus[2]));
										gpcWt.setgNum(Double.valueOf(valus[4]));
										gpcWt.setgBType(Long.valueOf(valus[5]));
										gpcWt.setgIsC(Long.valueOf(valus[8]));
										gpcWt.setgIsB(Long.valueOf(valus[7]));
										gpcWtMapper.insert(gpcWt);
									}else{
										gpcWt.setgPrice(Double.valueOf(valus[2]));
										gpcWt.setgNum(Double.valueOf(valus[4]));
										gpcWt.setgBType(Long.valueOf(valus[5]));
										gpcWt.setgIsC(Long.valueOf(valus[8]));
										gpcWt.setgIsB(Long.valueOf(valus[7]));
										gpcWtMapper.updateById(gpcWt);
									}
								}
							}
						} catch (Exception e) {
							log.error("get jj data is error!" + e);
						}finally{
							httpGet.abort();
						}
					}
				}
			}
		}
	}
}